package pl.edu.pw.ee.buildcity.scheduler;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import pl.edu.pw.ee.buildcity.commons.exceptions.BuildCityRuntimeException;
import pl.edu.pw.ee.buildcity.scheduler.jobs.BuildJob;

import java.text.ParseException;
import java.util.Date;

/**
 * @author mgrzechocinski
 * @since 2009-10-11
 */
public class BuildCityJobDetail extends JobDetail {

	private static final Logger log = Logger.getLogger(BuildCityJobDetail.class);

	private static final long serialVersionUID = 1L;

	public static final String DEFAULT_JOBS_GROUP = "buildcity";
	public static final String DEFAULT_TRIGGERS_GROUP = "buildcity";
	public static final String TRIGGERS_PREFIX = "tx";

	private CronTrigger cronTrigger;

	public BuildCityJobDetail(String jobName) {
		setDurability(true);
		setName(jobName);
		setJobClass(BuildJob.class);
		setGroup(DEFAULT_JOBS_GROUP);
	}

	public BuildCityJobDetail withCronTrigger(String cronExpr) {
		if (StringUtils.isBlank(cronExpr)) {
			log.warn("Giver cron expression is blank! Cron trigger NOT ADDED to job " + getName());
			return this;
		}
		try {
			cronTrigger = new CronTrigger(TRIGGERS_PREFIX + getName(), DEFAULT_TRIGGERS_GROUP, getName(), DEFAULT_JOBS_GROUP, cronExpr);
			cronTrigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);
		} catch (ParseException e) {
			throw new BuildCityRuntimeException(e.getMessage());
		}
		return this;
	}

	public CronTrigger getCronTrigger() {
		return cronTrigger;
	}

	public String getCronExpr() {
		return cronTrigger != null ? cronTrigger.getCronExpression() : null;
	}

	public Date getNexFireTime() {
		return cronTrigger != null ? cronTrigger.getNextFireTime() : null;
	}

	public boolean hasTrigger() {
		return cronTrigger != null;
	}

	public void cancelTrigger() {
		this.cronTrigger = null;
	}

	@Override
	public String toString() {
		return getName();
	}
}
